<?php

/**
 * HtmlierTest
 *
 * @author vbolshov
 */

use km\util\Htmlier;

use \PHPUnit_Framework_TestCase;

require_once dirname(__FILE__) . '/../../lib/km/util/Htmlier.php';

class HtmlierTest extends PHPUnit_Framework_TestCase {
	function testStripTags()
	{
		$h = new Htmlier();
		$h->setAllowedTags('');
		// text that is not wrapped into any tag, will be wrapped in <p> - by DomDocument
		$this->assertEquals('<p>xxx</p>', $h->filter('<a onclick="asdf"><b>xxx<d></r></a>'));
		
		$h->setAllowedTags('<a>');
		$this->assertEquals('<a href="">xxx</a>', $h->filter('<a href=""><b>xxx<d></r></a>'));
	}
	function testSimpleStripAttributes()
	{
		$h = new Htmlier();
		$h->setAllowedTags('<a>');
		$h->setDisallowedAttributes(array('style'));
		$this->assertEquals('<a href="">xxx</a>', $h->filter('<a style="asdf" href="">xxx</a>'));
	}
	function testStripAttributesByWildCard()
	{
		$h = new Htmlier();
		$h->setAllowedTags('<a>');
		$h->setDisallowedAttributeRegexps(array('/^on.+/i'));
		$this->assertEquals('<a href="">xxx</a>', $h->filter('<a onclick="dirty_function()" href="">xxx</a>'));
	}
	function testInvalidMarkup()
	{
		$h = new Htmlier();
		$h->setAllowedTags('<p><a><i>');
		$this->assertEquals('<p><a><i>text</i></a></p>', $h->filter('<p><a><i>text</p></a>'));
		$this->assertEquals('<p><a><i>text</i></a></p>', $h->filter('<p><a><i>text</p></i></a>'));
	}
	function testTypography()
	{
		$h = new Htmlier();
		$h->setAllowedTags('<p>');
		$this->assertEquals('<p>&larr; &mdash; &rarr;</p>', $h->filter('<p><- - -></p>'));
		
		$h->setTypograhy(false);
		$this->assertEquals('<p>&lt;- - -&gt;</p>', $h->filter('<p><- - -></p>'));
	}

	function testHyperlinks()
	{
		$h = new Htmlier();
		$h->setAllowedTags('<p>');
		$this->assertEquals('<p><a href="http://www.php.net/p/?x=y&amp;y=x#f">http://www.php.net/p/?x=y&amp;y=x#f</a></p>', $h->filter('<p>http://www.php.net/p/?x=y&y=x#f</p>'));
		
		$h->setHyperlinks(false);
		$this->assertEquals('<p>http://www.php.net/p/?x=y&amp;y=x#f</p>', $h->filter('<p>http://www.php.net/p/?x=y&y=x#f</p>'));
	}
	
	function testAntiXssFilter()
	{
		$h = new Htmlier();
		$h->setAllowedTags('<p><a>');
		$this->assertEquals('<p>' . $h->getXssReplacer() . '</p>', $h->filter('<p><a href="javascript:alert(\'hacked\');">a</a></p>'));
	}
	
	function testSpecialChars()
	{
		$h = new Htmlier();
		$h->setAllowedTags('<p>');
		$this->assertEquals('<p>xx &gt;&lt; x</p>', $h->filter('<p>xx >< x</p>'));
	}
	
	function testTextWrappedInPreIsAlwaysEscaped()
	{
		$h = new Htmlier();
		$h->setAllowedTags('<pre>');
		$this->assertEquals('<pre> (x&lt;y) &lt;&gt; (y&gt;x) </pre>', $h->filter('<pre> (x<y) <> (y>x) </pre>'));
	}
}
